package it.progettoso.activity;

import it.progettoso.utility.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;	
import android.widget.EditText;
import android.widget.Toast;


public class ConfigurationActivity extends Activity {
	private View startButton,exitButton;
	private View info1,info2,info3,info4,info5,info6,info7,info8,info9,info10,info11;
	
	private Context context=this;
	private EditText txt_oldPassword;
	private EditText txt_newPassword;
	private String old_password="";
	private String user_password="";
	private String new_password="";
	private boolean flag_exist;
	private Resources res;
	MenuItem c1,c2;


	private EditText txt_info ,txt_callme,txt_infocam ,txt_infolocationGPS,
	txt_infolocationWiFi,txt_playalarm , txt_lock ,txt_unlock,txt_number,txt_attemps,txt_mail;

	private String[] commands={
			DBConnection.INFO_COMMAND,DBConnection.LOCATION_COMMAND,
			DBConnection.WIFILOCATION_COMMAND,DBConnection.CAM_COMMAND,
			DBConnection.PLAYALARM_COMMAND,DBConnection.CALLME_COMMAND,DBConnection.LOCK_COMMAND,DBConnection.UNLOCK_COMMAND};


	private String[] data={
			DBConnection.FRIEND_NUMBER,DBConnection.ATTEMPS,
			DBConnection.EMAIL};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.configuration_layout);
		compileCommandText();

		startButton = (View)findViewById(R.id.button_go);
		exitButton = (View)findViewById(R.id.button_exit);
		exitButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ConfigurationActivity.this.finish();
			}
		});
		startButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				controlloSimNumber();
				String[] codes=readCodesFromUser();
				String[] value=readValueFromUser();
				if(codes!= null && value!=null){
					popolateTableData(data,value,data.length);
					popolaTableCommands(commands, codes, commands.length);
					ConfigurationActivity.this.finish();
				}else{
					return;
				}
			}
		});
		
		info1 = (View)findViewById(R.id.info_v1);
		info1.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog_desc(R.string.desc_friendNumber);
			}
		});
		info2 = (View)findViewById(R.id.info_v2);
		info2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog_desc(R.string.desc_attemps);
			}
		});
		info3 = (View)findViewById(R.id.info_v3);
		info3.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog_desc(R.string.desc_yourEmail);
			}
		});
		info4 = (View)findViewById(R.id.info_v4);
		info4.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog_desc(R.string.desc_infosmartphone);
			}
		});
		info5 = (View)findViewById(R.id.info_v5);
		info5.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog_desc(R.string.desc_infolocationGPS);
			}
		});
		info6 = (View)findViewById(R.id.info_v6);
		info6.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog_desc(R.string.desc_infolocation);
			}
		});
		info7 = (View)findViewById(R.id.info_v7);
		info7.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog_desc(R.string.desc_infocam);
			}
		});
		info8 = (View)findViewById(R.id.info_v8);
		info8.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog_desc(R.string.desc_playalarm);
			}
		});
		info9 = (View)findViewById(R.id.info_v9);
		info9.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog_desc(R.string.desc_callme);
			}
		});
		info10 = (View)findViewById(R.id.info_v10);
		info10.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog_desc(R.string.desc_lock);
			}
		});
		info11= (View)findViewById(R.id.info_v11);
		info11.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog_desc(R.string.desc_unlock);
			}
		});
	}

	protected void dialog_desc(int desc) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("Descrizione attributo");
		builder.setMessage(desc);
		builder.setCancelable(false);
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		c1=menu.add("Imposta PIN Applicazione");
		c2=menu.add("Info");
		//Per impostare un icona ai pulsanti del menu
		//c1.setIcon(R.drawable.pin_icon);
		c2.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setTitle("Info Android Recovery");
				builder.setMessage(R.string.info_comandi);
				builder.setCancelable(false);
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				builder.create().show();
				return true;
			}
		});

		c1.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				final Dialog changePasswordDialog = new Dialog(context);
				changePasswordDialog.setTitle("Cambio password");

				changePasswordDialog.setContentView(R.layout.psw_layout);
				changePasswordDialog.setCancelable(false);				

				Button confirm = (Button)changePasswordDialog.findViewById(R.id.psw_buttonConfirm);
				Button exit = (Button)changePasswordDialog.findViewById(R.id.psw_buttonExit);
				txt_oldPassword = (EditText) changePasswordDialog.findViewById(R.id.psw_txtOldPassword);
				txt_newPassword = (EditText) changePasswordDialog.findViewById(R.id.psw_txtNewPassword);

				confirm.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						flag_exist=false;
						res= getResources();
						user_password = txt_oldPassword.getText().toString();
						DBConnection db = new DBConnection(context);
						if(db.open()){
							String pintmp=db.readData(DBConnection.PIN);		
							if(pintmp==null || pintmp==""){
								old_password = res.getString(R.string.PIN);
							}else if(pintmp.length()<1){
								old_password = res.getString(R.string.PIN);
							}else{
								old_password = pintmp;
								flag_exist=true;
							}
							if(old_password.equals(user_password)){
								new_password=txt_newPassword.getText().toString();
								if(new_password==null || new_password==""){
									Toast.makeText(context, "Inserire un nuovo PIN", Toast.LENGTH_LONG).show();
								}else if(new_password.length()<1){
									Toast.makeText(context, "Inserire un nuovo PIN", Toast.LENGTH_LONG).show();
								}else{
									if(flag_exist){
										db.updateData(DBConnection.PIN, new_password);
										Toast.makeText(context, "Password aggiornata: "+new_password, Toast.LENGTH_LONG).show();
										changePasswordDialog.dismiss();
									}else{
										db.insertData(DBConnection.PIN, new_password);
										Toast.makeText(context, "Nuova pass: " + new_password, Toast.LENGTH_LONG).show();
										changePasswordDialog.dismiss();
									}
								}

							}else{
								Toast.makeText(context, "Inserire corrett la vecchia pass!", Toast.LENGTH_LONG).show();
							}
							db.close();
						}else{
							changePasswordDialog.dismiss();
						}
					}
				});
				exit.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						changePasswordDialog.dismiss();
					}
				});

				changePasswordDialog.show();
				return true;
			}
		});

		return true;

	}
	public String[] readValueFromUser() {

		String f_number= "", attemps="",mail= "";
		txt_number = (EditText)findViewById(R.id.info_EditFriedNumber);
		txt_attemps = (EditText)findViewById(R.id.info_EditAttemps);
		txt_mail = (EditText)findViewById(R.id.info_EditMail);

		f_number = txt_number.getText().toString();
		attemps = txt_attemps.getText().toString();
		mail = txt_mail.getText().toString();
		if(f_number==null || attemps==null || mail ==null){
			return null;
		}
		if(f_number.length()<10){
			Toast.makeText(this, "Attenzione: Num Tel deve essere > 9 cifre", Toast.LENGTH_LONG).show();
			return null;
		}
		if(attemps.length()<1){
			Toast.makeText(this, "Inserisci il numero di tentativi di accesso consentiti", Toast.LENGTH_LONG).show();
			return null;
		}		
		if(mail.length()<11){
			Toast.makeText(this, "E Mail non valida", Toast.LENGTH_LONG).show();
			return null;
		}

		String[] list={f_number,attemps,mail};
		return list;

	}

	public String[] readCodesFromUser() {
		String mess_err_length="I codici obbigatori devono contentere piu di 2 cifre";
		String mess_err="Riempi i campi obbligatori";

		String info="", infolocationGPS="",infolocationWiFi="",
		infocam= "", playalarm= "", callme= "", lock= "",unlock= "";

		txt_info = (EditText)findViewById(R.id.txt_infosmartphone);
		txt_callme = (EditText)findViewById(R.id.txt_callme);
		txt_infocam = (EditText)findViewById(R.id.txt_infocam);
		txt_infolocationGPS = (EditText)findViewById(R.id.txt_infolocation);
		txt_infolocationWiFi=(EditText)findViewById(R.id.txt_infolocationWiFi);
		txt_playalarm = (EditText)findViewById(R.id.txt_playalarm);
		txt_lock = (EditText)findViewById(R.id.txt_lock);
		txt_unlock = (EditText)findViewById(R.id.txt_unlock);

		info= (String)txt_info.getText().toString();
		infolocationGPS= (String)txt_infolocationGPS.getText().toString();
		infolocationWiFi= (String)txt_infolocationWiFi.getText().toString();
		infocam= (String)txt_infocam.getText().toString();
		playalarm= (String)txt_playalarm.getText().toString();
		callme= (String)txt_callme.getText().toString();
		lock= (String)txt_lock.getText().toString();
		unlock= (String)txt_unlock.getText().toString();

		if(info==null || infocam==null ||infolocationWiFi==null ||
				playalarm==null || callme==null || lock ==null || unlock==null){
			Toast.makeText(this, mess_err, Toast.LENGTH_LONG).show();
			return null;
		}

		if(info.length()<2 || infocam.length()<2 || infolocationWiFi.length()<2 ||
				playalarm.length()<2 || callme.length()<2 || lock.length()<2 || unlock.length()<2){
			Toast.makeText(this, mess_err_length, Toast.LENGTH_LONG).show();
			return null;
		}else{
			String[] list={info,infolocationGPS,infolocationWiFi,
					infocam,playalarm,callme,lock,unlock};
			return list;
		}	
	}
	public void popolaTableCommands(String[] commands,String[] codes,int num) {
		DBConnection db = new DBConnection(this.getApplicationContext());
		if(db.open()){
			for(int i=0;i<num;i++){
				if (db.readCommand(commands[i])!=null && db.readCommand(commands[i]).length()>1){
					db.updateCommand(commands[i], codes[i]);
				}else{
					db.insertCommand(commands[i], codes[i]);
				}
			}
			db.close();
		}
	}

	public void popolateTableData(String[]name,String[] value,int num){
		String mess="Nuovi dati salvati";

		DBConnection db = new DBConnection(this.getApplicationContext());
		if(db.open()){
			for(int i=0;i<num;i++){
				//Se il dato gia esiste
				if(db.readData(name[i])!=null && db.readData(name[i]).length()>0){
					//Fai l'ggiornamento
					db.updateData(name[i], value[i]);
				}else{
					//Fai l'inserimento
					db.insertData(name[i], value[i]);
				}
			}
			db.close();
			Toast.makeText(this.getApplicationContext(), mess, Toast.LENGTH_LONG).show();
		}
	}


	private void controlloSimNumber(){
		TelephonyManager mtm= (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
		String serialNumber=mtm.getSimSerialNumber();
		String mySerialNumber=null;
		String messok = "SERIAL SIM cambiato con successo.";

		if(serialNumber==null){
			return;
		}
		DBConnection db = new DBConnection(this.getApplicationContext());
		if(db.open()){
			mySerialNumber = db.readData(DBConnection.SIM_SERIAL_NUMBER);
			if(mySerialNumber == null || mySerialNumber==""){
				db.insertData(DBConnection.SIM_SERIAL_NUMBER, serialNumber);
			}else{
				if(!isEqualSerial(serialNumber,mySerialNumber)){
					//Se il dato gia esiste fai l'aggiornamentio
					db.updateData(DBConnection.SIM_SERIAL_NUMBER, serialNumber);
					Toast.makeText(this, messok, Toast.LENGTH_SHORT).show();
				}
			}
			db.close();
		}
	}

	private boolean isEqualSerial(String serialNumber,String mySerialNumber){
		if(serialNumber.equals(mySerialNumber))
			return true;
		else
			return false;		
	}

	public void compileCommandText(){
		DBConnection db = new DBConnection(this.getApplicationContext());
		if(db.open()){
			EditText txt_friendnum =(EditText) findViewById(R.id.info_EditFriedNumber);
			String a1=db.readData(DBConnection.FRIEND_NUMBER);
			if(a1!="" || a1!=null)
				txt_friendnum.setText(a1);

			EditText txt_attemps = (EditText) findViewById(R.id.info_EditAttemps);
			String a2=db.readData(DBConnection.ATTEMPS);
			if(a2!="" || a2!=null)
				txt_attemps.setText(a2);

			EditText txt_email = (EditText) findViewById(R.id.info_EditMail);
			String a3=db.readData(DBConnection.EMAIL);
			if(a3!="" || a3!=null)
				txt_email.setText(a3);


			EditText txt_infoSmartphone = (EditText)findViewById(R.id.txt_infosmartphone);
			String s1=db.readCommand(DBConnection.INFO_COMMAND);
			if(s1!="" || s1!=null)
				txt_infoSmartphone.setText(s1);

			EditText txt_infoLocation = (EditText)findViewById(R.id.txt_infolocation);
			String s3=db.readCommand(DBConnection.LOCATION_COMMAND);
			if(s3!="" || s3!=null)
				txt_infoLocation.setText(s3);

			EditText txt_infoLocationWiFi = (EditText)findViewById(R.id.txt_infolocationWiFi);
			String s3_2=db.readCommand(DBConnection.WIFILOCATION_COMMAND);
			if(s3_2!="" || s3_2!=null)
				txt_infoLocationWiFi.setText(s3_2);

			EditText txt_infoCam = (EditText)findViewById(R.id.txt_infocam);
			String s4=db.readCommand(DBConnection.CAM_COMMAND);
			if(s4!="" || s4!=null)
				txt_infoCam.setText(s4);

			EditText txt_playalarm = (EditText)findViewById(R.id.txt_playalarm);
			String s5=db.readCommand(DBConnection.PLAYALARM_COMMAND);
			if(s5!="" || s5!=null)
				txt_playalarm.setText(s5);

			EditText txt_callMe = (EditText)findViewById(R.id.txt_callme);
			String s6=db.readCommand(DBConnection.CALLME_COMMAND);
			if(s6!="" || s6!=null)
				txt_callMe.setText(s6);

			EditText txt_lock = (EditText)findViewById(R.id.txt_lock);
			String s7=db.readCommand(DBConnection.LOCK_COMMAND);
			if(s7!="" || s7!=null)
				txt_lock.setText(s7);

			EditText txt_unlock = (EditText)findViewById(R.id.txt_unlock);
			String s8=db.readCommand(DBConnection.UNLOCK_COMMAND);
			if(s8!="" || s8!=null)
				txt_unlock.setText(s8);

		}
		db.close();
	}


}